package org.javaexpert.spaces.masterworker.swingui;

import org.javaexpert.spaces.masterworker.TaskMonitor;
import org.javaexpert.spaces.masterworker.TaskStatusData;
import static org.javaexpert.spaces.masterworker.TaskStatusData.TaskStatus.PENDING;
import static org.javaexpert.spaces.util.SpaceUtils.findSpace;
import static org.javaexpert.spaces.util.SpaceUtils.findTransactionManager;
import org.javaexpert.spaces.util.TransactionTemplate;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Vector;

public class TaskStatus {
    private TaskMonitor monitor;
    private boolean showPendingFinished = true;

    private void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final DefaultTableModel tableModel = new DefaultTableModel();

        final Vector columns = new Vector() {
            {
                add("Id");
                add("GroupId");
                add("Finished");
                add("Consumed");
                add("Status");
                add("WorkerId");
                add("Retry Count");
                add("Duration");
                add("Started");
                add("Finished");
                add("Comment");
            }
        };
        JTable table = buildTable(tableModel, columns);

        JPanel main = new JPanel(new BorderLayout());
        frame.getContentPane().add(main);
        main.add(new JScrollPane(table), BorderLayout.CENTER);
        JPanel bottom = buildBottomPanel(tableModel, columns);
        main.add(bottom, BorderLayout.SOUTH);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    private JPanel buildBottomPanel(final DefaultTableModel tableModel, final Vector columns) {
        JPanel bottom = new JPanel(new FlowLayout());

        bottom.add(new JButton("Refresh") {
            {
                addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        tableModel.setDataVector(fetchData(monitor), columns);

                    }
                });
            }
        });
        bottom.add(new JCheckBox("Show PENDING/FINISHED") {
            {
                addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        showPendingFinished = isSelected();
                        tableModel.setDataVector(fetchData(monitor), columns);

                    }
                });
                setSelected(showPendingFinished);
            }
        });
        return bottom;
    }


    private JTable buildTable(DefaultTableModel tableModel, Vector columns) {
        JTable table = new JTable();
        TableSorter sorter = new TableSorter(tableModel);
        table.setModel(sorter);
        sorter.setTableHeader(table.getTableHeader());
        tableModel.setDataVector(fetchData(monitor), columns);
        table.setShowHorizontalLines(true);
        table.getTableHeader().setVisible(true);
        return table;
    }

    private Vector fetchData(TaskMonitor monitor) {
        Vector res = new Vector();
        final Long now = System.currentTimeMillis();
        for (final TaskStatusData s : filterData(monitor.taskStatuses())) {
            res.add(new Vector() {
                {
                    long duration;
                    if (s.finishTime != null) {
                        duration = s.finishTime.getTime() - s.startTime.getTime();
                    } else {
                        duration = s.startTime == null ? 0 : now - s.startTime.getTime();
                    }

                    add(s.taskId);
                    add(s.groupId);
                    add(s.finished);
                    add(s.consumed);
                    add(s.status);
                    add(s.workerId);
                    add(s.retryCount);

                    add(duration / 1000);
                    add(s.startTime);
                    add(s.finishTime);
                    add(s.comment);
                }
            });
        }
        return res;

    }

    private java.util.List<TaskStatusData> filterData(final Iterable<TaskStatusData> data) {
        java.util.List<TaskStatusData> res = new ArrayList<TaskStatusData>();
        for (TaskStatusData d : data) {
            if (!showPendingFinished && (d.status == PENDING || d.finished)) {
                continue;
            }
            res.add(d);
        }
        return res;
    }

    public TaskStatus() throws Exception {
        monitor = new TaskMonitor(findSpace("mySpace", "localhost"), new TransactionTemplate(findTransactionManager("localhost")), "bag1");
    }

    public static void main(String[] args) throws Exception {

        new TaskStatus().createAndShowGUI();
    }
}
